package com.example.spring.security.demo.filter;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.example.spring.security.demo.entity.MyUserDetails;
import com.example.spring.security.demo.utils.JwtUtil;
import com.example.spring.security.demo.utils.MyStringUtils;
import com.example.spring.security.demo.utils.RedisCache;
import com.example.spring.security.demo.utils.UserUtils;
import io.jsonwebtoken.Claims;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

/**
 * @ClassName MyJwtAuthenticationTokenFilter
 * @Description
 * @Author lichuanqi
 * @Date 2022/5/14 14:36
 * @Version 1.0
 **/
//@Component
public class MyJwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    private RedisCache redisCache;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        //TODO：判断接口是否是匿名访问

        String token = request.getHeader("token");
        if (MyStringUtils.isBlank(token)){
            filterChain.doFilter(request, response);
            //TODO: 如何返回自定义异常
            return;
        }

        try {
            Claims claims = JwtUtil.parseJWT(token);
            String userId = claims.getSubject();
            MyUserDetails userDetails =  redisCache.getCacheObject(UserUtils.getUserIdCacheKey(userId));
            if (Objects.isNull(userDetails)){
                throw new RuntimeException("用户未登录");
            }


            //将认证信息放入SecurityContextHolder，
            //表示用户已经认证成功后面的过滤器不会再进行认证
            UsernamePasswordAuthenticationToken authenticationToken =
                    new UsernamePasswordAuthenticationToken(userDetails,
                            null,
                            userDetails.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            filterChain.doFilter(request, response);
        } catch (RuntimeException e){
            throw e;
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("执行过滤器出错");
        }

    }
}
